package com.zjy.web.intecepter;

import cn.dev33.satoken.stp.StpUtil;
import com.zjy.common.constant.BusinessConstant;
import com.zjy.common.constant.StatusEnums;
import com.zjy.common.domain.dto.RequestInfoDto;
import com.zjy.common.domain.model.RequestHolder;
import com.zjy.common.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @author zhangjianyu
 * email: 578547270@qq.com
 * create_time: 2024-10-22 12:11
 * description:
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CollectorInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestInfoDto info = new RequestInfoDto();
        info.setIp(ServletUtils.getClientIP());
        if (StpUtil.isLogin()) {
            long userId = StpUtil.getLoginIdAsLong();
            Object userTypeObj = StpUtil.getExtra(BusinessConstant.LOGIN_USER_TYPE_KEY);
            if (userTypeObj != null && Objects.equals(userTypeObj.toString(), StatusEnums.LOGIN_USER_TYPE_ADMIN.getStatusStr())) {
                info.setAdminUserId(userId);
            }
        }
        RequestHolder.set(info);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }
}
